package aidn.animation.controller 
{
	import aidn.animation.utils.PatternFilter;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.IBitmapDrawable;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Rectangle;
	
	/**
	 * 
	 * 
	 */
	public class PatternManager 
	{
		
		private var _pfilter :PatternFilter;
		private var _target  :DisplayObjectContainer;
		
		private var _patternRect :Rectangle;
		
		private var _nx :int;
		private var _ny :int;
		
		private var _dx :int;
		private var _dy :int;
		
		public function PatternManager() 
		{
			
		}
		
		/**
		 * パターンを描画する対象をセットします。
		 * @param	target
		 */
		public function setTarget ( target :DisplayObjectContainer ) :void
		{
			_target = target;
			_nx = _target.x;
			_ny = _target.y;
		}
		
		/**
		 * パターンをセットします。
		 * @param	pattern		Array or IBitmapDrawable
		 * @param	rect		範囲
		 */
		public function setPattern ( pattern :*, rect :Rectangle = null ) :void
		{
			if (pattern is Array)
			{
				if ( ! rect )	rect = new Rectangle(0, 0, pattern[0].length, pattern.length);
				_patternRect = rect;
				
				if (!_pfilter) _pfilter = new PatternFilter();
				_pfilter.setArray( pattern );
			}
			else
			{
				if ( ! rect )	rect = new Rectangle(0, 0, pattern.width, pattern.height);
				_patternRect = rect;
				
				if (!_pfilter) _pfilter = new PatternFilter();
				_pfilter.setObj( pattern, rect );
			}
		}
		
		/**
		 * スクロールを開始します。
		 * @param	dx
		 * @param	dy
		 * @param	w
		 * @param	h
		 */
		public function scrollStart ( dx :int, dy :int, w :int, h :int ) :void
		{
			_dx = dx;
			_dy = dy;
			
			var rect :Rectangle = new Rectangle(   - _patternRect.width,   - _patternRect.height,
												 w + _patternRect.width, h + _patternRect.height);
			
			_pfilter.setFilter( _target, rect );
			_target.addEventListener( Event.ENTER_FRAME, _enterFrameHandler );
		}
		
		private function _enterFrameHandler ( evt :Event ) :void 
		{
			_target.x += _dx;
			_target.y += _dy;
			
			     if (0 < _dx && _nx + _patternRect.width <= _target.x)		_resetPosition();
			else if (_dx < 0 && _target.x <= _nx + _patternRect.width)		_resetPosition();
			
			     if (0 < _dy && _ny + _patternRect.height <= _target.y)		_resetPosition();
			else if (_dy < 0 && _target.y <= _ny + _patternRect.height)		_resetPosition();
		}
		
		private function _resetPosition ( ) :void
		{
			_target.x = _nx;
			_target.y = _ny;
			
		}
	}
}